﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Wicresoft.UnifyShow.Business;
using Microsoft.Practices.Unity;
using Wicresoft.UnifyShow2.Portal;
using Wicresoft.UnifyShow2.Portal.Models;
using System.Configuration;
using Wicresoft.UnifyShow.Portal2.ViewModels;
using Wicresoft.UnifyShow.Business.Extensions;

namespace Wicresoft.UnifyShow.Portal.Controllers
{
    [Authorize]
    public class AdminPermissionController : BaseController
    {
        private IUser_X user;
        private ISiteBranch siteBranch;
        private IPlanManagement planManagement;
        private IAlert alertService;
        private readonly string CompanyName = "福建省烟草专卖局";

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user).Dispose();
            ((IDisposable)siteBranch).Dispose();
            ((IDisposable)planManagement).Dispose();
            ((IDisposable)alertService).Dispose();
        }

        [InjectionConstructor]
        public AdminPermissionController(IUser_X user, ISiteBranch siteBranch, IPlanManagement planManagement, IAlert alert)
        {
            this.user = user;
            this.siteBranch = siteBranch;
            this.planManagement = planManagement;
            this.alertService = alert;
        }


        //
        // GET: /AdminPermission/

        public ActionResult Index(int page = 1, string sort = "DisplayName", string sortDir = "Ascending", string name = "", string displayname = "")
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);

            int pageSize = 10;

            Decimal totalRecords;
            string companyName = USER_X.Company;
            IEnumerable<User_XModel> users = null;
            if (companyName != null && string.Equals(companyName, CompanyName))
            {
                users = user.GetListPageAndSortUser_X(out totalRecords, pageSize, page, sort, sortDir, name, displayname);
            }
            else
            {
                users = user.GetListPageAndSortUser_X(out totalRecords, companyName, pageSize, page, sort, sortDir, name, displayname);
            }

            ViewBag.name = name;
            ViewBag.displayname = displayname;

            PagedUser_XsModel model = new PagedUser_XsModel
            {
                PageSize = pageSize,
                PageNumber = page,
                User_Xs = users,
                TotalRows = totalRecords
            };
            return View(model);
        }

        public JsonResult GetDepartment(string company)
        {
            List<string> departmentlist = new List<string>();
            if (!string.IsNullOrEmpty(company))
            {
                departmentlist = DepartmentHelper.GetListDepartment(company);
            }

            return Json(departmentlist, JsonRequestBehavior.AllowGet);
        }

        //----------------------修改-------------------------------------------------------------------------------------------
        public ActionResult UserInfo(int userID)
        {
            PermissionModel m = new PermissionModel();
            SFUser_XModel u = user.GetUserByIDSF(userID);
            m.UserID = int.Parse(u.ID.ToString());
            m.LoginID = u.Name;
            m.IsConfigAdmin = u.IsAdmin == 1 ? true : false;
            m.IsLeader = u.IsLeader == 1 ? true : false;
            m.IsAccessUS = u.AccessUS == 1 ? true : false;
            m.IsAccessITSM = u.AccessITSM == 1 ? true : false;
            m.IsAccessGJ = u.AccessGJ == 1 ? true : false;
            m.UserName = u.DisplayName;
            m.Position = u.Position;
            m.UserDepartment = u.Department;
            m.UserSite = u.Company;
            m.Mobile = u.Mobile;
            m.Email = u.Email;
            m.IsRelevance = false;
            m.PeopleNo = u.PeopleNo;
            // 判断用户和地市中间表中是否存在用户和所在公司的关联项
            if (user != null)
            {
                var sites = user.GetSiteBranchByID(userID);
                if (sites.Count > 0 && sites.FirstOrDefault(s => s.Name == u.Company) != null)
                {
                    m.IsRelevance = true;
                }
            }


            //查询登录用户的在统一展现系统所有有权限的地市
            List<SiteBranchModel> listSites = siteBranch.GetSiteBranchByUserID(userID);
            //查询登录用户的在告警系统所有有权限的地市
            List<SiteBranchModel> listSites_gj = siteBranch.GetSiteBranch_GJByUserID(userID);
            //查询所有的地市
            List<SiteBranchModel> allSites = siteBranch.GetSiteALLBranch().Where(o => !string.IsNullOrWhiteSpace(o.Alias)).ToList();
            //给用户在统一展现系统和告警系统的地市权限赋值
            List<US_SiteAccessModel> us_SiteAccessList = new List<US_SiteAccessModel>();
            List<GJ_SiteAccessModel> gj_SiteAccessList = new List<GJ_SiteAccessModel>();
            foreach (var item in allSites)
            {
                US_SiteAccessModel usmodel = new US_SiteAccessModel();
                usmodel.ID = item.ID;
                usmodel.Alias = item.Alias;
                usmodel.IsAccess = listSites.Where(o => o.ID == item.ID).Count() >= 1;
                us_SiteAccessList.Add(usmodel);
                GJ_SiteAccessModel gjmodel = new GJ_SiteAccessModel();
                gjmodel.ID = item.ID;
                gjmodel.Alias = item.Alias;
                gjmodel.IsAccess = listSites_gj.Where(o => o.ID == item.ID).Count() >= 1;
                gj_SiteAccessList.Add(gjmodel);
            }
            m.US_SiteAccessList = us_SiteAccessList;
            m.GJ_SiteAccessList = gj_SiteAccessList;

            ViewData["Departments"] = DepartmentHelper.GetListDepartment(u.Company).ToList().Select(c => new SelectListItem { Value = c, Text = c });
            ViewData["DepartmentSelect"] = u.Department;

            return PartialView(m);
        }

        public ActionResult UserEdit(int userID)
        {
            return PartialView(((PartialViewResult)UserInfo(userID)).Model);
        }

        //------修改----------------
        [HttpPost]
        public ActionResult UserEdit(PermissionModel model)
        {
            List<decimal> roles_us = new List<decimal>();
            List<decimal> roles_gj = new List<decimal>();
            List<US_SiteAccessModel> us_SiteAccessList = model.US_SiteAccessList;
            List<GJ_SiteAccessModel> gj_SiteAccessList = model.GJ_SiteAccessList;
            var userdepartment = string.Empty;
            if (Request.Form["DepartmentSelect"] != null)
            {
                userdepartment = Request.Form["DepartmentSelect"].ToString();
            }

            foreach (var item in us_SiteAccessList)
            {
                if (item.IsAccess)
                {
                    roles_us.Add(item.ID);
                }
            }

            foreach (var item in gj_SiteAccessList)
            {
                if (item.IsAccess)
                {
                    roles_gj.Add(item.ID);
                }
            }

            var sf = new SFUser_XModel();

            sf.ID = model.UserID;
            sf.IsAdmin = model.IsConfigAdmin == true ? 1 : 0;
            sf.IsLeader = model.IsLeader == true ? 1 : 0;
            sf.AccessUS = model.IsAccessUS == true ? 1 : 0;
            sf.AccessITSM = model.IsAccessITSM == true ? 1 : 0;
            sf.AccessGJ = model.IsAccessGJ == true ? 1 : 0;
            sf.Name = model.LoginID;

            sf.Department = userdepartment;
            sf.Position = model.Position;
            sf.Mobile = model.Mobile;
            sf.Email = model.Email;
            sf.Disabled = model.Disabled ? 1 : 0;
            sf.PeopleNo = model.PeopleNo;

            if (model != null && model.IsRelevance == true)
            {
                user.UpdateUserSiteTable(sf);
            }

            if (model != null && model.IsRelevance == false)
            {
                user.DeleteUserSiteInfo(sf);
            }
            var json = user.UpdateRoleByUserID(sf, roles_us, roles_gj);
            bool ret = planManagement.SyncInternalGroupUser();
            return Json(json);
            //return PartialView(model);
        }
        public ActionResult ChangePassword()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult ChangePassword(string login, string pass)
        {
            return Json(user.ChangePassword(login, pass));
        }

        public ActionResult CreateUser()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);
            var model = new SFUser_XModel()
            {
                Company = USER_X.Company
            };


            model.IsRelevance = true;
            ViewBag.Post = false;
            if (string.Equals(USER_X.Company, CompanyName))
            {
                ViewData["Sites"] = siteBranch.GetSiteALLBranch().Select(o => o.Name).ToList();
            }
            else
            {
                ViewData["Sites"] = siteBranch.GetSiteBranchByUserID(Convert.ToInt32(USER_X.ID)).Select(o => o.Name).ToList();
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult CreateUser(SFUser_XModel model)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            string resultStr = string.Empty;
            ViewBag.Post = true;
            ViewBag.Status = user.Create(model, out resultStr);
            ViewBag.ResultStr = resultStr;
            ViewData["Sites"] = siteBranch.GetSiteALLBranch().Select(o => o.Name).ToList();
            bool ret = planManagement.SyncInternalGroupUser();
            return View(model);
        }

        [HttpPost]
        public ActionResult Exist(string name)
        {
            return Json(user.Exist(name.ToLower()));
        }

        public JsonResult quickAccessAdmin()
        {
            base.SetRoles(user);
            //get user info
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var sites = user.GetSiteBranchByID(USER_X.ID);
            var mySite = sites.FirstOrDefault(x => x.Name == USER_X.Company);
            if (mySite == null)
            {
                throw new Exception("UserSite is null.");
            }

            Random random = new Random();
            string rnd = "?nocatch=" + DateTime.Now.Millisecond + random.Next(1000);

            JsonCollection root = new JsonCollection();
            //创建用户
            JsonObject itsm = new JsonObject();
            itsm.MergeProperty("text", new JsonConstant("创建用户"));
            itsm.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr = new JsonObject();
            attr.MergeProperty("url", new JsonConstant(Url.Action("CreateUser", "AdminPermission") + rnd));
            itsm.MergeProperty("attributes", attr);
            root.AppendObject(itsm);

            //配置用户
            JsonObject self = new JsonObject();
            self.MergeProperty("text", new JsonConstant("配置用户"));
            self.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr2 = new JsonObject();
            attr2.MergeProperty("url", new JsonConstant(Url.Action("Index", "AdminPermission") + rnd));
            self.MergeProperty("attributes", attr2);
            root.AppendObject(self);

            //添加业务系统
            JsonObject monitor = new JsonObject();
            monitor.MergeProperty("text", new JsonConstant("添加业务系统"));
            monitor.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr3 = new JsonObject();
            attr3.MergeProperty("url", new JsonConstant(Url.Action("Add", "AdminBS") + rnd));
            monitor.MergeProperty("attributes", attr3);
            root.AppendObject(monitor);

            //维护业务系统
            JsonObject report = new JsonObject();
            report.MergeProperty("text", new JsonConstant("维护业务系统"));
            report.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr4 = new JsonObject();
            attr4.MergeProperty("url", new JsonConstant(Url.Action("Index", "AdminBSMaintain") + rnd));
            report.MergeProperty("attributes", attr4);
            root.AppendObject(report);

            if (IsConfigAdmin && mySite.Alias.Equals("省局"))
            {
                //常用资源管理
                JsonObject comSource = new JsonObject();
                comSource.MergeProperty("text", new JsonConstant("常用资源管理"));
                comSource.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attr6 = new JsonObject();
                attr6.MergeProperty("url", new JsonConstant(Url.Action("Admin", "ComResource") + rnd));
                comSource.MergeProperty("attributes", attr6);
                root.AppendObject(comSource);

                //运维报告管理
                JsonObject Ops = new JsonObject();
                Ops.MergeProperty("text", new JsonConstant("运维报告管理"));
                Ops.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject _report = new JsonObject();
                _report.MergeProperty("url", new JsonConstant(Url.Action("Admin", "OpsReport") + rnd));
                Ops.MergeProperty("attributes", _report);
                root.AppendObject(Ops);
            }

            //值班计划
            JsonObject dutyPlan = new JsonObject();
            dutyPlan.MergeProperty("text", new JsonConstant("值班计划管理"));
            dutyPlan.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr7 = new JsonObject();
            attr7.MergeProperty("url", new JsonConstant(Url.Action("Index", "DutyPlan") + rnd));
            dutyPlan.MergeProperty("attributes", attr7);
            root.AppendObject(dutyPlan);

            //计划管理数据维护
            JsonCollection planChildren = new JsonCollection();

            //省局管理员才能看见
            if (IsConfigAdmin && mySite.Alias.Equals("省局"))
            {
                //电子公告
                JsonObject Announcement = new JsonObject();
                Announcement.MergeProperty("text", new JsonConstant("电子公告"));
                Announcement.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attr8 = new JsonObject();
                attr8.MergeProperty("url", new JsonConstant(Url.Action("Announcement", "PlanManagement") + rnd));
                Announcement.MergeProperty("attributes", attr8);
                root.AppendObject(Announcement);

                //大屏挂起告警展示
                JsonObject ShowView = new JsonObject();
                ShowView.MergeProperty("text", new JsonConstant("大屏展示维护"));
                ShowView.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attr_showview = new JsonObject();
                attr_showview.MergeProperty("url", new JsonConstant(Url.Action("ShowViewConfig", "AdminPermission") + rnd));
                ShowView.MergeProperty("attributes", attr_showview);
                root.AppendObject(ShowView);


                //第三方巡检类型
                JsonObject thirdType = new JsonObject();
                thirdType.MergeProperty("text", new JsonConstant("第三方巡检类型"));
                thirdType.MergeProperty("iconCls", new JsonConstant("icon-edit"));
                JsonObject attr9 = new JsonObject();
                attr9.MergeProperty("url", new JsonConstant(Url.Action("ConfigInspection", "PlanManagement") + rnd));
                thirdType.MergeProperty("attributes", attr9);

                planChildren.AppendObject(thirdType);
            }

            ////维护ITSM区县受派成员
            //JsonObject group = new JsonObject();
            //group.MergeProperty("text", new JsonConstant("维护ITSM区县受派人员"));
            //group.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            //JsonObject attr10 = new JsonObject();
            //attr10.MergeProperty("url", new JsonConstant("http://10.188.238.22:8080/arsys/forms/10.188.238.23/CFG%3AStandardConsole/Default+User+View/?cacheid=8172cc24"));
            //group.MergeProperty("attributes", attr10);
            //root.AppendObject(group);

            //计划接口人
            JsonObject interfacePeople = new JsonObject();
            interfacePeople.MergeProperty("text", new JsonConstant("计划接口人"));
            interfacePeople.MergeProperty("iconCls", new JsonConstant("icon-edit"));
            JsonObject attr_interface = new JsonObject();
            attr_interface.MergeProperty("url", new JsonConstant(Url.Action("ConfigInterfacePeople", "PlanManagement") + rnd));
            interfacePeople.MergeProperty("attributes", attr_interface);


            planChildren.AppendObject(interfacePeople);

            //计划任务组
            JsonObject taskGroup = new JsonObject();
            taskGroup.MergeProperty("text", new JsonConstant("计划任务组"));
            taskGroup.MergeProperty("iconCls", new JsonConstant("icon-edit"));
            JsonObject attr_taskGroup = new JsonObject();
            attr_taskGroup.MergeProperty("url", new JsonConstant(Url.Action("ConfigGroup", "PlanManagement") + rnd));
            taskGroup.MergeProperty("attributes", attr_taskGroup);

            planChildren.AppendObject(taskGroup);

            JsonObject planManage = new JsonObject();
            planManage.MergeProperty("text", new JsonConstant("计划管理数据维护"));
            planManage.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            planManage.MergeProperty("children", planChildren);
            root.AppendObject(planManage);




            ////添加故障分类
            //JsonObject breakdown = new JsonObject();
            //breakdown.MergeProperty("text", new JsonConstant("添加故障分类"));
            //breakdown.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            //JsonObject attr7 = new JsonObject();
            //attr7.MergeProperty("url", new JsonConstant(Url.Action("Add", "AdminBD")+ rnd));
            //breakdown.MergeProperty("attributes", attr7);
            //root.AppendObject(breakdown);

            ////维护故障分类
            //JsonObject modifybreakdown = new JsonObject();
            //modifybreakdown.MergeProperty("text", new JsonConstant("维护故障分类"));
            //modifybreakdown.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            //JsonObject attr8 = new JsonObject();
            //attr8.MergeProperty("url", new JsonConstant(Url.Action("Index", "AdminBDMaintain")+ rnd));
            //modifybreakdown.MergeProperty("attributes", attr8);
            //root.AppendObject(modifybreakdown);

            ////添加操作系统分类
            //JsonObject os = new JsonObject();
            //os.MergeProperty("text", new JsonConstant("添加操作系统分类"));
            //os.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            //JsonObject attr9 = new JsonObject();
            //attr9.MergeProperty("url", new JsonConstant(Url.Action("Add", "AdminOS")+ rnd));
            //os.MergeProperty("attributes", attr9);
            //root.AppendObject(os);

            ////维护操作系统分类
            //JsonObject modifyos = new JsonObject();
            //modifyos.MergeProperty("text", new JsonConstant("维护操作系统分类"));
            //modifyos.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            //JsonObject attr10 = new JsonObject();
            //attr10.MergeProperty("url", new JsonConstant(Url.Action("Index", "AdminOSMaintain")+ rnd));
            //modifyos.MergeProperty("attributes", attr10);
            //root.AppendObject(modifyos);




            return new NRemedy.MVC.UI.RawJsonResult()
            {
                Data = root.ToString(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        public ActionResult ShowViewConfig()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            var includePending = alertService.HasIncludePendingAlert();

            return View(includePending);
        }

        public JsonResult UpdateIncludePendingAlert(decimal result)
        {
            var returnVal = alertService.UpdateIncludePendingAlert(result);

            return Json(returnVal ? "OK" : "Error", JsonRequestBehavior.AllowGet);
        }
    }
}
